//===========================================================================
/*!
 *  \file main.cc
 *
 *  \brief 
 *  
 *  \author  Nguyen Quoc Chinh
 *  \date    2007-01-25
 *
 */
//===========================================================================


#include "PotFitter.h"
#include <fstream>

/// global variables 
const char HELP[]="\n \
	NAME:  benchOF - benchmark forcefields \n\
	SYNOPSIS \n\
		benchOF -i[format] [input file]  [OPTION] \n\n\
	DIPSCRIPTION\n\
		[format]=  f ---> XYZ format \n\
					g03 ---> Gaussian output format \n\
					l ---> XYZ format of lattice \n\
					car ---> Accelys format file \n\
					\n\
		-ff [force field]: can be one of water forcefields \n\
				OSS2 : (default) \n\
				TTM2F, TTMT21F, TTM3F :  TTM family \n\
					or atomic models (openbabel required ) \n\
				Ghemical,    //Ghemical force field. \n\
 				MMFF94, //   MMFF94 force field. \n\
 				MMFF94s,   // MMFF94s force field. \n\
 				UFF,    // Universal Force Field \n\
 					or lattice forcefields (ttm_ice required) \n\
				TTM21F_ICE, TTM3F_ICE, QSPCFW_ICE, SPCF_ICE \n\n\
		-a [parameter]:  parameter files \n\n\
		-u [unit]: unit=0,1,2 for HARTREE(default),KCALMOL and KJMOL, respectively.\n\n\
		 \n\n";


string fnOut="";

bool bBound=false;

int nRuns=0,debug=0;

vector<string> arList;

void potFitting();
	

int main(int argc,char **argv){	
	time_t duration=time(0);
	
	
	
	if(!isatty(0)){ string s; while(cin>>s) arList.push_back(s);}	
	
	for(int i=1;i<argc;i++){ arList.push_back(string(argv[i]));}
		
	for(int i=0;i<arList.size();i++){
		string ar=arList[i];		

		//parameters of output
		if(ar=="-o"){ fnOut=arList[i+1];}		

		if(ar=="-nRuns"){ 
			sscanf(arList[i+1].c_str(),"%d",&nRuns);  			
		}			
		
		//parameters for potfitting
		if(ar=="-bound"){ bBound=true;};
		
		if(ar=="-v"){ sscanf(arList[i+1].c_str(),"%d",&debug); }
			
		if(ar=="-h"){ cout<<HELP;return 0; }
	}
	
	
	//----------------
	potFitting(); //using levmar package to reparameterize
	

	duration=time(0)-duration;	
	cout<<" Finished successfully in "<<duration<<" secs! "<<endl;

	return 0;
}


void potFitting(){	
	cout<<" Initializing ... \n\n";
	
	PotFitter fit(arList);	
	
	cout<<"\n Origin values : \n";	fit.evaluate(5);	
	
	cout<<"\n Running with "<<nRuns<<" iterations "<< endl;
	if(nRuns==0) return ;
	
	fit.RunLevMar(nRuns,bBound,debug);
	 
	cout<<"\n Final values \n";	fit.evaluate(5);
	
	cout<<"\n Solution: \n";
	
	if(fnOut!=""){ 
		ofstream fout(fnOut.c_str());
		fit.printParam(fout);
		fout.close();
	}
	
	fit.printParam(cout);	
}
